<?php

namespace app\middleware;

use think\facade\Cache;
use think\facade\Db;
use Closure;

class AuthMiddleware
{
    public function handle($request, Closure $next)
    {
        $token = $request->header('Authorization');
        
        if (!$token) {
            return json([
                'code' => 401,
                'message' => '未提供认证token'
            ]);
        }
        
        $token = str_replace('Bearer ', '', $token);
        $userId = $this->getUserIdFromToken($token);
        
        if (!$userId) {
            return json([
                'code' => 401,
                'message' => '无效的token'
            ]);
        }
        
        // 验证token是否有效
        $cachedToken = Cache::get('user_token_' . $userId);
        if ($cachedToken !== $token) {
            return json([
                'code' => 401,
                'message' => 'token已过期'
            ]);
        }
        
        // 将用户ID添加到请求中
        $request->userId = $userId;
        
        return $next($request);
    }
    
    private function getUserIdFromToken(string $token): ?int
    {
        try {
            $parts = explode('.', $token);
            if (count($parts) !== 2) {
                return null;
            }
            
            $payload = json_decode(base64_decode($parts[0]), true);
            return $payload['user_id'] ?? null;
            
        } catch (\Exception $e) {
            return null;
        }
    }
}